import random
from django.http import HttpResponse
from django.shortcuts import render
from utils.tencent.sms import send_sms_single
from django.conf import settings


def send_sms(request):
    """ 发送短信
        ?tpl=login  -> 548762
        ?tpl=register -> 548760
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)
    res = send_sms_single('15131289', template_id, [code, ])
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])

from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError        
class RegisterModelForm(forms.ModelForm):
    phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ], widget=forms.TextInput(attrs={'placeholder': '请输入手机号'}))
    password = forms.CharField(label='密码', widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
    re_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(attrs={'placeholder': '请再次输入密码'}))
    code = forms.CharField(label='验证码', widget=forms.TextInput(attrs={'placeholder': '请输入验证码'}))



    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 为用户名和邮箱添加placeholder
        self.fields['username'].widget.attrs['placeholder'] = '请输入用户名'
        self.fields['email'].widget.attrs['placeholder'] = '请输入邮箱'

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 're_password', 'phone', 'code']



def register(request):
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})


def test_redis(request):
    """测试Redis连接和操作"""
    from utils.redis import get_redis_client
    redis_client = get_redis_client()

    # 测试设置和获取字符串
    redis_client.set('test_key', 'Hello Redis!')
    test_value = redis_client.get('test_key')

    # 测试设置和获取JSON
    user_info = {'username': 'test_user', 'email': 'test@example.com'}
    redis_client.set_json('user_info', user_info, expire=3600)
    stored_user_info = redis_client.get_json('user_info')

    # 测试哈希表操作
    redis_client.hset('user:1', 'name', '张三')
    redis_client.hset('user:1', 'age', '25')
    user_name = redis_client.hget('user:1', 'name')
    user_age = redis_client.hget('user:1', 'age')
    all_user_info = redis_client.hgetall('user:1')

    result = {
        'string_test': {'key': 'test_key', 'value': test_value},
        'json_test': {'key': 'user_info', 'value': stored_user_info},
        'hash_test': {
            'name': user_name,
            'age': user_age,
            'all_info': all_user_info
        }
    }

    return HttpResponse(f"Redis测试结果: {result}")
